package org.gnome.wsgalaxy.gnodroid;

import android.util.Log;

import org.json.JSONObject;

import java.io.InputStream;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.ArrayList;

//用于管理服务和启动服务
public class ServiceManager {
    public ServiceManager()
    {
        // registe every service here
        __registeService("Connection", ServiceConnection.class);
        __registeService("Infomation", ServiceInfomation.class);
        __registeService("Appmanager", ServiceAppmanager.class);
    }

    //启动一个后台线程，在线程中匹配和启动服务
    public void
    startService(Socket socket)
    {
        (new ServiceRunner(socket)).start();
    }

    //存放服务的动态数组
    private ArrayList<ServiceId> m_serviceList = new ArrayList<>();

    //注册服务 LOCK
    private synchronized void
    __registeService(String name, Class serviceClass)
    {
        m_serviceList.add(new ServiceId(name, serviceClass));
    }

    //获取服务 LOCK
    private synchronized Class
    __matchService(String name)
    {
        for (ServiceId sid : m_serviceList) {
            if (sid.name.equals(name)) {
                return sid.serviceClass;
            }
        }
        return  null;
    }

    //服务的相关信息
    private class ServiceId
    {
        public ServiceId(String n, Class sc)
        {
            name = n;
            serviceClass = sc;
        }
        public String name;
        public Class serviceClass;
    }

    //用于运行服务的后台线程
    private class ServiceRunner extends Thread
    {
        private Socket m_socket = null;

        public ServiceRunner(Socket socket)
        {
            m_socket = socket;
        }

        public void
        run()
        {
            try {
                //设置超时为5秒
                m_socket.setSoTimeout(5000);
                InputStream inStream = m_socket.getInputStream();
                byte[] buffSize = new byte[4];
                //获取数据长度
                if(inStream.read(buffSize) == -1) {
                    //m_socket.close();
                    throw new Exception("socket close");
                }
                ByteBuffer byteBufferSize = ByteBuffer.wrap(buffSize);
                byteBufferSize.order(ByteOrder.BIG_ENDIAN);
                int size = byteBufferSize.getInt();
                byte[] buffData = new byte[size];
                int readSize = 0;
                int curReadSize = 0;
                while (true) {
                    curReadSize = inStream.read(buffData, readSize, size-readSize);
                    if (curReadSize == -1) {
                        throw new Exception();
                    }

                    readSize += curReadSize;

                    if (readSize == size) {
                        break;
                    }
                }

                String name = __getName(buffData);
                //get service by name
                Class serviceClass = __matchService(name);
                if (serviceClass == null) {
                    throw new Exception("can not match a service");
                }
                //create and start service in current thread
                ServiceBase service = (ServiceBase) serviceClass.newInstance();
                service.start(buffData, m_socket);
            } catch (Exception e) {
                Log.d("gnd", e.toString());
            }
            finally {
                try {m_socket.close();} catch (Exception e) {}
            }
        }

        //从json中获取名字
        private String
        __getName(byte[] data)
        {
            String resultStr = new String();
            try {
                String jsonStr = new String(data, "UTF-8");
                JSONObject json = new JSONObject(jsonStr);
                resultStr = json.getString("service");
            } catch (Exception e) {} finally {}
            return resultStr;
        }

    }
}
